package com.andova.component.net.converter.gson;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2018-08-13.
 *
 * @author kzaxil
 * @since 1.0.0
 */
public class GsonConverterFactory extends Converter.Factory {
    /**
     * 解决:
     * 1)要{}后端给[]返回实例对象
     * 2)要[]后端给{}返回空数组
     * 3)要int.class, Integer.class,short.class, Short.class,long.class, Long.class,double.class, Double.class,
     * float.class, Float.class后端给的非数字类型返回0
     * 4)要String后端给了[],{}等类型返回""
     * <p>该接口使用容错的GSON</p>
     */
    // TODO: 2018-12-12 目前遇到一个问题，如果POJO数据类型为int，而实际数据类型为double，则会出现数据解析出错
    // 而经过测试发现，如果出现上面的情况，实际gson会判定其为String类型，进而调用StringUtils#toInt(String)
    public static GsonConverterFactory create() {
        return create(GsonBeanFactory.newGson());
    }

    public static GsonConverterFactory create(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        return new GsonConverterFactory(gson);
    }

    private final Gson gson;

    private GsonConverterFactory(Gson gson) {
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new GsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new GsonRequestBodyConverter<>(gson, adapter);
    }
}
